import { deleteSpecTemplate, specTemplateList } from "@/services/stock-goods/specTemplateApi";
import { showMsg } from "@/utils/utils";
import ProTable, { ActionType, ProColumns } from "@ant-design/pro-table";
import { Button, Col, FormInstance, Input, Modal, Popconfirm, Row } from "antd";
import { useRef, useState } from "react";
import SpecForm from "./SpecForm";

const SpecificationTemplate = (props: ModalProps) => {

  const { open, onOpenChange, onSelected } = props;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [modalFormOpen, setModalFormOpen] = useState<boolean>(false);
  const [editRowData, setEditRowData] = useState<STOCKGOODSAPI.SpecTemplate>();
  const [selectedRowData, setSelectedRowData] = useState<STOCKGOODSAPI.SpecTemplate>();
  const [loading, setLoading] = useState<boolean>(false);

  const columns: ProColumns<STOCKGOODSAPI.SpecTemplate>[] = [
    {
      title: '模板名称',
      dataIndex: 'template_name',
      formItemProps: { label: false, style: { display: 'none' } }
    },
    {
      title: '规格概述',
      dataIndex: 'temp_summary',
      search: false
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      search: false,
      width: 140
    },
    {
      title: '操作',
      width: 130,
      align: 'center',
      valueType: 'option',
      render: (_, value) => [
        <a key="edit" onClick={() => { setEditRowData(value); setModalFormOpen(true); }}>编辑</a>
        ,
        <Popconfirm key="del" placement="topRight" title='确认删除？' onConfirm={async () => {
          setLoading(true);
          deleteSpecTemplate(value.template_id).catch(err => showMsg(err?.data?.errmsg)).finally(() => setLoading(false));
        }}>
          <a>删除</a>
        </Popconfirm>
      ]
    }
  ];

  const onSearch = (value: string) => {
    formRef.current?.setFieldsValue({ 'template_name': value });
    formRef.current?.submit();
  };

  const onOk = () => {
    if (!selectedRowData) {
      showMsg('请选择模板');
      return;
    }
    onSelected(selectedRowData);
    onOpenChange(false);
  };

  return <>
    <Modal
      width="60%"
      visible={open}
      maskClosable={false}
      onCancel={() => onOpenChange(false)}
      onOk={onOk}
      title="选择规格模板"
      okText="选择"
    >
      <Row style={{ padding: '12px 0 0', alignItems: "center" }} >
        <Col>
          <span>模板名称：</span>
        </Col>
        <Col span={12}>
          <Input.Search size="small" allowClear placeholder="请输入模板名称" style={{ verticalAlign: 'text-top' }} onSearch={onSearch} enterButton />
        </Col>
        <Col style={{ marginLeft: 'auto' }}>
          <Button size="small" onClick={() => { setEditRowData(null as any); setModalFormOpen(true); }} type="primary">新增模板</Button>
        </Col>
      </Row>
      <ProTable<STOCKGOODSAPI.SpecTemplate>
        rowKey="template_id"
        actionRef={actionRef}
        formRef={formRef}
        columns={columns}
        loading={loading}
        options={false}
        pagination={{ size: "small" }}
        search={{ optionRender: false }}
        bordered
        request={async params => {
          setLoading(true);
          try {
            const res = await specTemplateList({ ...params });
            return { success: true, data: res.record_list, total: res.sum_record_num };
          } catch (error: any) {
            showMsg(error?.data?.errmsg);
            return { success: false, data: [] };
          } finally {
            setLoading(false);
          }
        }}
        rowSelection={{
          type: "radio",
          columnTitle: "当前使用",
          columnWidth: 70,
          onSelect: setSelectedRowData
        }}
      />
      <SpecForm open={modalFormOpen} rowData={editRowData} onOpenChange={open => {
        if (!open) {
          actionRef.current?.reload();
        }
        setModalFormOpen(open);
      }} />
    </Modal>
  </>;
};

type ModalProps = {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSelected: (data: STOCKGOODSAPI.SpecTemplate) => void
}

export default SpecificationTemplate;
